<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { propTypes } from '@jctech/utils/propTypes';
import { isNullOrWhiteSpece } from '@jctech/utils/is';
import { CommonService } from '@jctech/api/services/common';

const props = defineProps({
  src: propTypes.string.def(''),
  objectId: propTypes.string.def(''),
  defaultWidth: propTypes.string.def('100'),
  defaultHeight: propTypes.string.def('100'),
  useBase64: propTypes.bool.def(false),
  useUrl: propTypes.bool.def(false),
  watchEvent: propTypes.bool.def(false),
  usingCache: propTypes.bool.def(false)
});

defineOptions({
  name: 'CImg'
});

const imgRef = ref(null);

const content = ref(null);
const url = ref('');
const ImageSrc = computed(() => {
  if (props.src) {
    return props.src;
  }
  if (props.objectId && !props.useBase64 && url.value) {
    return url.value;
  }
  return content.value;
});

const makeDefaultImage = () =>
  CommonService.getInstance<CommonService>().GetDefaultImg(props.defaultWidth, props.defaultHeight);

const loadImg = (isForce = false) => {
  if (props.useBase64) {
    if (!isNullOrWhiteSpece(props.objectId)) {
      CommonService.getInstance<CommonService>()
        .GetImage(props.objectId)
        .then((img) => {
          content.value = img;
        });
    } else {
      content.value = makeDefaultImage();
    }
  } else {
    if (!isNullOrWhiteSpece(props.objectId)) {
      CommonService.getInstance<CommonService>()
        .GetImageOfObject(props.objectId)
        .then((obj) => {
          if (obj && obj.ImgUrl) {
            url.value = obj.ImgUrl;
          } else {
            url.value = null;
            content.value = makeDefaultImage();
          }
        });
    } else {
      content.value = makeDefaultImage();
    }
  }
};

watch(
  () => props.objectId,
  () => {
    loadImg();
  },
  { immediate: true }
);
</script>

<template>
  <img ref="imgRef" :src="ImageSrc" />
</template>

<style lang="less"></style>
